import {
  wxChooseImage,
  editUserInfo,
} from "../../../api/recharge/recharge";
import {
  timeoutTask,
  showWxToast,
  showWxLoading,
  hideWxLoading,
} from "../../../utils/index";
import qiniu from "../../../utils/qiniu/index";

let originAvator = "";
const app = getApp();

Page({
  data: {
    deskList: [],
    statusList: [
      "话痨",
      "傻白甜",
      "单身贵族",
      "高富帅",
      "屌丝",
      "钻石王老五",
      "高冷勿扰",
      "白富美",
      "中二少年",
    ],
    formData: {
      avator: "",
      wx_name: "",
      table_number: "",
      position: "",
    },
    avatorIconDeleteVisible: false,
  },
  onLoad: function (options) {
    const tmpData = this.data.formData;
    tmpData.avator = options.headImg;
    tmpData.wx_name = options.nickname;
    tmpData.table_number = options.deskNum;
    tmpData.position = options.currentStatus;
    originAvator = tmpData.avator;
    this.setData({
      formData: tmpData,
    });
    
    // 初始化七牛云token
    this.initQiniu();
    
    const tmpDesckList = [];
    for (let i = 0; i < 90; i += 1) {
      if (i < 3) {
        tmpDesckList.push(i + 1);
      } else if (i < 12) {
        tmpDesckList.push(i + 2);
      } else if (i < 21) {
        tmpDesckList.push(i + 3);
      } else if (i < 30) {
        tmpDesckList.push(i + 4);
      } else if (i < 39) {
        tmpDesckList.push(i + 5);
      } else if (i < 48) {
        tmpDesckList.push(i + 6);
      } else if (i < 57) {
        tmpDesckList.push(i + 7);
      } else if (i < 66) {
        tmpDesckList.push(i + 8);
      } else if (i < 75) {
        tmpDesckList.push(i + 9);
      } else if (i < 84) {
        tmpDesckList.push(i + 10);
      } else {
        tmpDesckList.push(i + 11);
      }
    }
    this.setData({
      deskList: tmpDesckList,
    });
  },
  onShow: function () {},
  onUnload: function () {},
  
  // 初始化七牛云token
  initQiniu: function() {
    qiniu
      .getQiniuToken()
      .then(res => {
        console.log('获取qiniu token成功', res);
        qiniu.initQiniu(res.data.token);
      })
      .catch(err => {
        console.log('获取qiniu token失败', err);
      });
  },
  handlePickerChange: function (e) {
    console.log(e.detail.value);
    let tmpFormData = this.data.formData;
    tmpFormData.table_number = this.data.deskList[e.detail.value];
    this.setData({
      formData: tmpFormData,
    });
  },
  chooseStatus: function (e) {
    console.log(e.currentTarget.dataset.status);
    let tmpFormData = this.data.formData;
    tmpFormData.position = e.currentTarget.dataset.status;
    this.setData({
      formData: tmpFormData,
    });
  },
  // 上传图片：选择本地 -> 立即上传 -> 得到服务器URL
  upload: function () {
    console.log("upload");
    let tempFilePaths;
    let tmpFormData = this.data.formData;
    const prevAvator = tmpFormData.avator;
    wxChooseImage()
      .then((res) => {
        console.log(res);
        tempFilePaths = res.tempFilePaths;
        // 先本地预览
        tmpFormData.avator = tempFilePaths[0];
        this.setData({
          formData: tmpFormData,
          avatorIconDeleteVisible: true,
        });
        this.isUploadingAvator = true;
        showWxLoading("头像上传中...");
        
        // 直接上传文件
        return qiniu.qiniuUpload(tempFilePaths[0]);
      })
      .then((res) => {
        console.log('qiniu上传成功', res);
        // 上传成功后，用服务器URL替换本地预览地址
        if (res && res.imageURL) {
          tmpFormData.avator = res.imageURL;
          this.setData({
            formData: tmpFormData,
          });
          showWxToast("头像上传成功");
        } else {
          // 返回不符合预期，恢复之前头像
          tmpFormData.avator = prevAvator;
          this.setData({
            formData: tmpFormData,
            avatorIconDeleteVisible: !!prevAvator,
          });
          showWxToast("头像上传失败");
        }
      })
      .catch((err) => {
        console.log(err);
        // 上传失败，恢复之前头像
        tmpFormData.avator = prevAvator;
        this.setData({
          formData: tmpFormData,
          avatorIconDeleteVisible: !!prevAvator,
        });
        showWxToast("头像上传失败");
      })
      .finally(() => {
        console.log("finally");
        hideWxLoading();
        this.isUploadingAvator = false;
      });
  },
  removeTempAvator: function () {
    let tmpFormData = this.data.formData;
    if (this.isUploadingAvator) {
      showWxToast("头像上传中，请稍后再试");
      return;
    }
    tmpFormData.avator = originAvator;
    this.setData({
      formData: tmpFormData,
      avatorIconDeleteVisible: false,
    });
  },
  handleNameBlur: function (e) {
    console.log(e.detail.value);
    let tmpFormData = this.data.formData;
    tmpFormData.wx_name = e.detail.value;
    this.setData({
      formData: tmpFormData,
    });
  },
  confirmEdit: function () {
    console.log(this.data.formData);
    let tmpFormData = this.data.formData;
    if (!tmpFormData.avator) {
      showWxToast("头像不能为空!");
      return;
    }
    if (!tmpFormData.wx_name) {
      showWxToast("姓名不能为空!");
      return;
    }
    if (!tmpFormData.table_number) {
      showWxToast("请选择桌号!");
      return;
    }
    if (!tmpFormData.position) {
      showWxToast("请选择身份!");
      return;
    }
    showWxLoading("信息修改中...");
    editUserInfo(this.data.formData)
      .then((res2) => {
        console.log(res2);
        hideWxLoading();
        if (res2.data.code === "200") {
          showWxToast("修改成功!");
          app.globalData.isH5NeedRefresh = true;
          timeoutTask(() => {
            wx.navigateBack({
              delta: 2,
            });
          }, 2000);
        }
      })
      .catch((err) => {
        console.log(err);
        hideWxLoading();
      });
  },
});
